import axios, { AxiosRequestConfig } from "axios";

type IConfig = {
  apiUrl: string;
  geweToken?: string;
};

export default class GeweChatSDK {
  private config: IConfig;

  constructor(config: { url: string; geweToken?: string }) {
    if (!config.url) {
      throw Error("请配置url 地址");
    }

    this.config = {
      apiUrl: config.url,
      geweToken: config.geweToken,
    };
  }

  async exec(
    command: string,
    params: any,
    option?: {
      method?: "POST" | "GET";
    },
  ): Promise<any> {
    const { apiUrl, geweToken } = this.config;

    const method = option?.method || "POST";

    const datas = JSON.stringify(params);

    const options: AxiosRequestConfig = {
      url: `${apiUrl}/${command}`,
      method,
      data: datas,
    };

    if (geweToken) {
      options.headers = {
        "X-GEWE-TOKEN": geweToken,
        "Content-Type": "application/json",
      };
    }

    console.log(JSON.stringify(options, null, 2), "optionsoptions");

    const { data } = await axios(options);

    return data;
  }
}
